package admin

import (
	"ginadmin/app/dao"
	"ginadmin/app/model"
	"net/http"
	"strings"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type IndexController struct {
	BaseController
}

func (con IndexController) Index(c *gin.Context) {

	c.HTML(http.StatusOK, "index/index.html", nil)
}

func (con IndexController) Main(c *gin.Context) {

	// c.JSON(http.StatusOK, gin.H{
	// 	"url":     c.Request.URL,
	// 	"uri":     c.Request.RequestURI,
	// 	"host":    c.Request.Host,
	// 	"path":    c.Request.URL.Path,
	// 	"rawpath": c.Request.Response,
	// })

	c.HTML(http.StatusOK, "index/main.html", nil)
}

// 退出登录
func (con IndexController) Logout(c *gin.Context) {

	session := sessions.Default(c)
	session.Set("adminId", nil)
	session.Save()

	con.Success(c, "退出成功")
}

// 获取菜单
func (con IndexController) Menu(c *gin.Context) {

	var menuapi = model.AdminMenuApis{}

	//todo 根据用户权限获取菜单
	roles := c.GetString("adminRoles")

	var roleslist []model.AdminRole

	dao.DB.Where("id in ?", strings.Split(roles, ",")).Find(&roleslist)

	var roleids = []string{}

	var issuperadmin = false

	for _, v := range roleslist {

		rules := strings.Split(v.Rules, ",")

		for _, r := range rules {
			if r == "*" {
				issuperadmin = true
			}

			roleids = append(roleids, r)
		}
	}

	if issuperadmin {
		dao.DB.Table("gin_admin_menu").Order("sort ASC").Where("is_show = ?", 1).Scan(&menuapi)
	} else {
		dao.DB.Table("gin_admin_menu").Order("sort ASC").Where("is_show = ?", 1).Where("id in ?", roleids).Scan(&menuapi)
	}

	treedata := menuapi.GetTree()

	c.JSON(http.StatusOK, treedata)
}
